package com.pig4cloud.pigx.strategy.feign;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import com.pig4cloud.pigx.strategy.api.feign.StrategyContractFeign;
import com.pig4cloud.pigx.strategy.entity.StrategySwitchContract;
import com.pig4cloud.pigx.strategy.enums.StrategySwitchContractEnum;
import com.pig4cloud.pigx.strategy.service.StrategyContractService;
import com.pig4cloud.pigx.strategy.vo.StrategyContractProfitVO;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * 策略模块-策略-合约feign接口实现类·
 *
 * @since 2022/11/26 14:44
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/feign/strategy/contract")
@Api(value = "strategy-contract", tags = "")
public class StrategyContractFeignImpl implements StrategyContractFeign {

	private final StrategyContractService strategyContractService;

	/**
	 * 根据产品id统计相关策略的条数
	 *
	 * @param productId 产品id
	 * @param from      标记系统内部请求
	 * @return {@link R< Long>}
	 * @since 2022/11/26 14:41
	 */
	@Inner
	@Override
	@GetMapping(COUNT_BY_PRODUCT_ID)
	public R<Long> countByProductId(@RequestParam("productId") Long productId, String from) {
		Long count = strategyContractService.countByProductId(productId);
		return R.ok(count);
	}

	/**
	 * 获取用户正在进行的策略数量
	 * @param userId 用户id
	 * @param from from
	 * @return r
	 */
	@Inner
	@Override
	@GetMapping(USER_START_STRATEGY_COUNT)
	public R<Long> userStartStrategyCount(@RequestParam("userId") Long userId, @RequestHeader(SecurityConstants.FROM) String from) {
		try {
			long count = new StrategySwitchContract().selectCount(new QueryWrapper<StrategySwitchContract>() {{
				in("status",
						StrategySwitchContractEnum.Status.RUNNING.getValue()
						,StrategySwitchContractEnum.Status.PAUSE.getValue()
						,StrategySwitchContractEnum.Status.ERROR.getValue());
				eq("user_id", userId);
			}});
			return R.ok(count);
		} catch (Exception e) {
			return R.ok(0L);
		}
	}

	@Inner
	@Override
	@GetMapping(USER_CONTRACT_PROFIT)
	public R<BigDecimal> userContractProfit(Long userId, String from) {
		StrategyContractProfitVO profit = strategyContractService.profit(userId);
		if (profit == null) {
			return R.ok(BigDecimal.ZERO);
		}
		return R.ok(profit.getProfitTotal());
	}
}
